﻿/*
'Copyright ?1995-2007, Camstar Systems, Inc. All Rights Reserved.
'Description:检验业务类
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer:Wangjh
'create Date:2020-5-25
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using uMES.LeanManufacturing.ParameterDTO;
using uMES.LeanManufacturing.DBUtility;
using System.Collections;
using System.Data;

namespace uMES.LeanManufacturing.ReportBusiness
{
   public class uMESContainerCheckBusiness
    {

        uMESCommonBusiness common = new uMESCommonBusiness();

        /// <summary>
        /// 获取待检验的数据
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public uMESPagingDataDTO GetCheckData(Dictionary<string, string> para)
        {
            string strSql = @"select distinct m.mfgorderid,m.processno,m.oprno,m.mfgordername,c.containerid,c.containername,pb.productname,p.description productdesc,sb.specname,s.specid,wt.qty,c.plannedstartdate,c.plannedcompletiondate,
                                     wt.reporttype,wt.reportdate,wt.workflowid,decode(wt.reporttype,0,'首检',3,'工序检验',1,'巡检',4,'入厂检验') reporttypename,wt.workreportinfoid,c.qty AS Conqty,c.childcount,c.qty as containerqty,
                                     c.uomid,c.productid ,w.workflowid AS currentFlowid,cus.factoryid,wt.ischecked,NVL(cci1.nonsenseqty,0) AS nonsenseqty
                            from workreportinfo wt
                            left join container c on c.containerid=wt.containerid
                            left join currentstatus cus on cus.currentstatusid = c.currentstatusid
                            left join workflowstep w on w.workflowstepid = cus.workflowstepid
                            left join mfgorder m on m.mfgorderid=c.mfgorderid
                            left join product p on p.productid=c.productid
                            left join productbase pb on pb.productbaseid=p.productbaseid
                            left join spec s on s.specid=wt.specid
                            left join specbase sb on sb.specbaseid=s.specbaseid
                            LEFT JOIN conventioncheckinfo cci1 on cci1.reportinfoid = wt.workreportinfoid
                            left join ConventionCheckInfo cci on cci.containerid=wt.containerid and cci.specid=wt.specid and cci.checktype=0--首检无记录
                            left join ContainerFinishInfo cf on cf.containerid= wt.containerid and cf.specid=wt.specid--无完工记录
                            where 1 = 1 AND c.finishstate IS NULL and c.containername<>c.containerid and c.qty>0
                            and cf.containerfinishinfoid is null
                            and wt.specid = (
                            SELECT NVL(sb.revofrcdid, wfs.specid) AS specid
                            FROM currentstatus cu
                            LEFT JOIN workflowstep wfs ON wfs.workflowstepid = cu.workflowstepid
                            LEFT JOIN specbase sb ON sb.specbaseid = wfs.specbaseid
                            WHERE cu.currentstatusid = c.currentstatusid
                            )";

            //and cci.conventioncheckinfoid is null

            if (para.ContainsKey("ProcessNo") && !string.IsNullOrWhiteSpace(para["ProcessNo"]))
            {
                strSql += string.Format(" and m.ProcessNo like '%{0}%'", para["ProcessNo"]);
            }

            if (para.ContainsKey("ProductName") && !string.IsNullOrWhiteSpace(para["ProductName"]))
            {
                strSql += string.Format(" and pb.ProductName like '%{0}%'", para["ProductName"]);
            }

            if (para.ContainsKey("ReportType") && !string.IsNullOrWhiteSpace(para["ReportType"]))//检验类型
            {
                strSql += string.Format(" and wt.ReportType={0}", para["ReportType"]);
            }

            if (para.ContainsKey("ContainerName") && !string.IsNullOrWhiteSpace(para["ContainerName"]))
            {
                strSql += string.Format(" and c.containername like '%{0}%' ", para["ContainerName"]);
            }

            if (para.ContainsKey("ScanContainerName") && !string.IsNullOrWhiteSpace(para["ScanContainerName"]))
            {
                strSql += string.Format(" and c.containername='{0}' ", para["ScanContainerName"]);
            }

            strSql += " order by wt.reportdate asc ";

            uMESPagingDataDTO result = new uMESPagingDataDTO();

            result = OracleHelper.GetPagingDataIns(strSql, int.Parse(para["CurrentPageIndex"]), int.Parse(para["PageSize"]));
            result.DBTable.Columns.Add("SpecNameDisp");
            result.DBTable.Columns.Add("checkedDisplay");

            for (int i = 0; i < result.DBTable.Rows.Count; i++)
            {
                result.DBTable.Rows[i]["checkedDisplay"] = "未检验";
                if (!string.IsNullOrEmpty(result.DBTable.Rows[i]["IsChecked"].ToString()))
                {
                    if (result.DBTable.Rows[i]["IsChecked"].ToString()=="1")
                    {
                        result.DBTable.Rows[i]["checkedDisplay"] = "已检验";
                    }
                }
            ;
                string strName = result.DBTable.Rows[i]["SpecName"].ToString();
                result.DBTable.Rows[i]["SpecNameDisp"] = common.GetSpecNameWithOutProdName(strName);

            }
            return result;

        }

        /// <summary>
        /// 保存检验数据
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public bool SaveCheckData(Dictionary<string,object> para) {
            string insertSql = @"insert into ConventionCheckInfo t (t.ConventionCheckInfoid,ConventionCheckInfoName,ContainerID,SpecID,ReportInfoID,CheckType,EligibilityQty,NonsenseQty,Notes,CheckEmployeeID,WorkflowID,CreateDate)
values('{0}','{1}','{2}','{3}','{4}','{5}',{6},{7},'{8}','{9}','{10}',sysdate)";
            string sql = "";
            ArrayList sqls = new ArrayList();

            sql = string.Format(insertSql,para["ConventionCheckInfoID"],para["ConventionCheckInfoName"],para["ContainerID"],para["SpecID"],para["ReportInfoID"],para["CheckType"],para["EligibilityQty"],
                para["NonsenseQty"],para["Notes"],para["CheckEmployeeID"],para["WorkflowID"]);

            sqls.Add(sql);

            string insertSql2 = @"insert into ConventionCheckProductNoInfo t(ConventionCheckProductNoInfoID,ConventionCheckInfoID,ContainerID,ContainerName,hgorbhg,productno)
values('{0}','{1}','{2}','{3}',{4},'{5}')";
            if (para.ContainsKey("ChildContainer"))
            {
                DataTable childDt = para["ChildContainer"] as DataTable;
                foreach (DataRow dr in childDt.Rows) {
                    sql = string.Format(insertSql2, Guid.NewGuid().ToString(), para["ConventionCheckInfoID"], dr["ContainerID"].ToString(), dr["ContainerName"].ToString(), 1, dr["ProductNo"].ToString());
                    sqls.Add(sql);
                }
            }
            if (para.ContainsKey("NonNo"))
            {
                DataTable childDt = para["NonNo"] as DataTable;
                foreach (DataRow dr in childDt.Rows)
                {
                    sql = string.Format(insertSql2, Guid.NewGuid().ToString(), para["ConventionCheckInfoID"], dr["ContainerID"].ToString(), dr["ContainerName"].ToString(), 0, dr["ProductNo"].ToString());
                    sqls.Add(sql);
                }
            }
            OracleHelper.ExecuteSqlTran(sqls);
           return true;

        }

        /// <summary>
        /// 判断是否有没走完的质量记录
        /// </summary>
        /// <param name="containerId"></param>
        /// <param name="workflowId"></param>
        /// <param name="specId"></param>
        /// <returns></returns>
        public ResultModel IsCompleteQuality(string containerId,string workflowId,string specId) {
            ResultModel re = new ResultModel(false,"");
            string strSql = @"select qr.qualityrecordinfoname,rp.* from qualityrecordinfo qr
left join rejectappqrinfo rj on rj.qualityrecordinfoid=qr.id
left join rejectappinfo rp on rp.id=rj.rejectappinfoid";
            strSql += string.Format(" where qr.containerid='{0}' and qr.workflowid='{1}'  and qr.specid='{2}' ",
                containerId,workflowId,specId);
            DataTable dt = OracleHelper.Query(strSql).Tables[0];

            foreach (DataRow dr in dt.Rows) {
                if (dr.IsNull("Status")) {
                    return new ResultModel(false, "有未提交不合格审理的质量记录");
                }
                if (Convert.ToInt32(dr["Status"])<40) {
                    return new ResultModel(false, "有未给出结论的不合格审理记录");
                }
                if (Convert.ToInt32(dr["fixqty"]) > 0) {
                    if (OracleHelper.QueryDataByEntity(new ExcuteEntity("repairinfo", ExcuteType.selectAll) {
                        strWhere=$" and rejectappinfoid='{dr["ID"].ToString()}' "
                    }).Rows.Count==0) {
                        return new ResultModel(false, "有需要返修的质量记录未做返修");
                    }
                }
                if (Convert.ToInt32(dr["scrapqty"]) > 0)
                {
                    if (OracleHelper.QueryDataByEntity(new ExcuteEntity("scrapinfo", ExcuteType.selectAll)
                    {
                        strWhere = $" and rejectappinfoid='{dr["ID"].ToString()}' "
                    }).Rows.Count == 0)
                    {
                        return new ResultModel(false, "有需要报废的质量记录未做报废");
                    }
                }
            }

            re.IsSuccess = true;
            return re;
        }
     }
}
